%%% File    : ddc.erl
%%% Author  : f355 <>
%%% Description : 
%%% Created :  2 Apr 2010 by f355 <>

-module(ddc).

-export([learn_and_reply/1, learn/1, reply/1, reply_random/0, read_logfile/1, dump_logfile/1, replay_log/0, test_reply/1]).

%% test function, prints 
test_reply(String) ->
    {ok, Res} = reply(String),
    io:format("~ts~n", [Res]).

learn_and_reply(String) ->
    Sentence=ddc_util:split(String),
    Result=reply(sentence, Sentence),
    add_log_entry(String),
    spawn(ddc_learn, learn, [Sentence, safe]),
    Result.

learn(String) ->
    Sentence=ddc_util:split(String),
    spawn(ddc_learn, learn, [Sentence, safe]).    

reply_random() ->
    reply(sentence, []).

reply(String) ->
    reply(string, String).

reply(string, String) ->
    Sentence=ddc_util:split(String),
    reply(sentence, Sentence);

reply(sentence, Sentence) ->
    Result=ddc_gen:gen_from_sentence(Sentence),
    case Result of
	{ok, Res} ->
	    {ok, ddc_util:post_process(Res)};
	Other -> Other
    end.

add_log_entry(String) ->
    ddc_db:run_query(fun() -> ddc_db:write_log(ddc_util:to_lower(String)) end, safe).

read_logfile(Name) ->
    case file:open(Name, [{encoding, unicode}]) of
	{ok, File} ->
	    read_log(File, 0),
	    file:close(File);
	Error -> Error
    end.

dump_logfile(Name) ->
    case file:open(Name, [write,{encoding, unicode}]) of
	{ok, File} ->
	    dump_log(File),
	    file:close(File);
	Error -> Error
    end.

read_log(IoDevice, Num) -> 
    case io:get_line(IoDevice, "") of
	{error, Why} -> {error, Num, Why};
	eof -> {ok, Num};
	Line ->
	    add_log_entry(lists:reverse(tl(lists:reverse(Line)))),
	    read_log(IoDevice, Num+1)
    end.

dump_log(IoDevice) ->
    F=fun(String)->
	      io:format(IoDevice,"~ts~n",[String]),
	      ok
      end,
    ddc_db:iterate_log(F).

replay_log() ->
    F=fun(String) ->
	      ddc_learn:learn(ddc_util:split(String), safe),
	      ok
	 end,
    ddc_db:iterate_log(F).

